package cn.pzaily.orange.producer.controller;

import cn.pzaily.orange.producer.service.OrangeProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @PackageName: cn.pzaily.orange.producer.controller
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-16 10:33
 */
@RestController
public class ServerController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrangeProductService orangeProductService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String hello() {
        return "orange-consumer:8008";
    }

    @RequestMapping(value = "/services", method = RequestMethod.GET)
    public Object services() {
        return discoveryClient.getInstances("orange-product");
    }

    @RequestMapping(value = "/discover")
    public Object discover() {
        return loadBalancerClient.choose("orange-product").getUri().toString();
    }

    @RequestMapping(value = "/call")
    public String call() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("orange-product");
        System.out.println("服务地址：" + serviceInstance.getUri());
        System.out.println("服务名称：" + serviceInstance.getServiceId());
        String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString(), String.class,"/");
        System.out.println(callServiceResult);
        return callServiceResult;
    }

    @RequestMapping(value = "/ribbon/call")
    public String rCall() {
        String result = restTemplate.getForObject("http://orange-product/", String.class);
        return result;
    }


    @RequestMapping(value = "/feign/call")
    public String fCall() {
        String hello = orangeProductService.hello();
        return hello;
    }

}
